﻿using System;
using System.Collections.Generic;
namespace NDI
{
    public class ContainerBuilder
    {
        private List<IRegistration> registrations = new List<IRegistration>();
        private Container container;

        #region BuildContaier
        public Container Build()
        {
            if (container == null)
            {
                container = new Container();
            }
            if (registrations != null && registrations.Count > 0)
            {
                foreach (Registration registration in registrations)
                {
                    ServiceKey key = new ServiceKey(registration.ServiceType, registration.FactoryType) { Name = registration.Name };
                    var entry = new ServiceEntry { Container = container, Factory = registration.Factory, Scope = registration.Scope, Owner = registration.Owner };
                    container.RegisterImpl(key, entry);
                }
                //注册完之后，清空以便下次注册
                registrations.Clear();
            }
            return container;
        }
        #endregion

        #region Register

        public IRegistration Register<TService>(Func<Container, TService> factory)
        {
            return RegisterImpl<TService, Func<Container, TService>>(factory);
        }

        public IRegistration Register<TService, TArg>(Func<Container, TArg, TService> factory)
        {
            return RegisterImpl<TService, Func<Container, TArg, TService>>(factory);
        }

        public IRegistration Register<TService, TArg, TArg1>(Func<Container, TArg, TArg1, TService> factory)
        {
            return RegisterImpl<TService, Func<Container, TArg, TArg1, TService>>(factory);
        }

        private IRegistration RegisterImpl<TService, TFunc>(TFunc factory)
        {
            var key = new ServiceKey(typeof(TService), typeof(TFunc));
            var registration = new Registration(typeof(TService), factory);
            registrations.Add(registration);
            return registration;
        }

        #endregion
    }
}
